/*
 * PageManager class 
 * Create by Charles Koh
 */

(function () {
	
	var PageManager = function (pages) {
		this.inFn = null;
		this.outFn = null;
		this.pages = null;
		this.menuPibot = null;
		this.currentShowPage = 0;
		this.init(pages);
	}
	
	PageManager.prototype = {
		handleEvent: function(event) {
			return false;
		},
		init: function(_pages){
			this.pages = _pages || document.getElementsByClassName('page')
		},
		switchTabMenu: function(page, url) {
			//if (typeof(this.inFn) == typeof(function(){}))		this.inFn();
			var pageObject;
			
			if (page >= 0 && page < this.pages.length) {
				addClass(this.pages[this.currentShowPage], "displayNone");
				this.currentShowPage = page;
				removeClass(this.pages[this.currentShowPage], "displayNone");
				pageObject = this.pages[this.currentShowPage];
			} else if (typeof(page) == "string") {
				pageObject = document.getElementById(page) || 0;
			} else if (typeof(page) == "object") {
				pageObject = page;
			}
			if (url && pageObject) {
				this.attachPage(pageObject, url); 
			}
			//if (typeof(this.outFn) == typeof(function(){}))		this.outFn();
		},
		getMenuByTitleName: function(title, option) {
			var result = null;
			var menuStack = [];
			var i=0, count = 0;
			if (typeof(option) == 'object') {
				result = option.pibot || /*this.menuPibot || */g_stringTemplate;
				count = option.count || 0;
			} else {
				result = /*this.menuPibot || */g_stringTemplate;
			}
			
			if (result.title && (result.contentId == title || result.title == title))	return result;
			while(result.menus) {
				while (i<result.menus.length) {
					if (result.menus[i].contentId == title || result.menus[i].title == title) {
						if (--count < 0) { 
							this.menuPibot = result.menus[i];
							return result.menus[i];
						}
					}
					if (result.menus[i].menus) {
						menuStack[menuStack.length] = {"index":i+1, "menu":result }; //{"title": result.title, "menus":result.menus}};
						result = result.menus[i];
						i = 0;
						continue;
					}
					i++;
				}
				if (menuStack.length > 0) {
					var data = menuStack.pop(); 
					result = data.menu;
					i = data.index;
				} else {
					break;
				}
			}
			return null;
		},
		attachPage: function(page, _url) {
			ajax.request({
				url: _url,
				type: "POST",
				dataType:"html",
				successCB: function (xhr) {
					switch(typeof(page)) {
						case "object":
						page.innerHTML = xhr;
						break;
						
						case "string":
						page = document.getElementById(page);
						if (page)	page.innerHTML = xhr;
						break;
					}
				},
				failCB: function () {
					
				}
			})
		},

	};
	
    if (typeof exports !== 'undefined') exports.PageManager = PageManager;
    else window.PageManager = PageManager;
})(); 
